<?php
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/5/4 14:31
 * 个人主页 : http://forpastime.com
 */

namespace App\Controller\Admin;

use App\Service\FileService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use App\Utils\Result;

/**
 * @AutoController(prefix="admin/ueditor")
 *
 * Class UeditorController
 * @package App\Controller\Admin
 */
class UeditorController
{
    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject()
     * @var FileService
     */
    protected $fileService;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $params = $request->all();

        switch ($params['action']) {

            case 'config':
                $result = $this->ueditorConfig();
                break;

            /* 上传图片 */
            case 'uploadimage':
                $result = $this->upload("image");
                break;
            /* 上传涂鸦 */
            case 'uploadscrawl':
                $result = $this->upload("image");
                break;
            /* 上传视频 */
            case 'uploadvideo':
                $result = $this->upload("video");
                break;
            /* 上传文件 */
            case 'uploadfile':
                $result = $this->upload("file");
                break;

            /* 列出图片 */
            case 'listimage':
                $result = "";
                break;
            /* 列出文件 */
            case 'listfile':
                $result = "";
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = "";
                break;

            default:
                $result = json_encode(['state' => '请求地址出错']);
                break;
        }

        /* 输出结果 */
        if (isset($params["callback"]) && false) {//TODO 跨域上传
            if (preg_match("/^[\w_]+$/", $params["callback"])) {
                echo htmlspecialchars($params["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode([
                    'state' => 'callback参数不合法'
                ]);
            }
        } else {
            if(isset($result['id']) && $result['id']>0){
                $data = [
                    'state'    => 'SUCCESS',
                    'url'      => $result['url'],
                    'title'    => $result['name'],
                    'original' => $result['name']
                ];
                return $response->json($data);
            }else if(isset($result['id']) && $result['id']==0){
                return Result::error('上传失败');
            }else{
                return $response->json(json_decode($result));
            }
        }
    }

    public function upload()
    {
        $fileController = new FileController();
        $file = $this->request->file("upfile");

        $categoryId = $this->request->input('category_id',0);
        $data = $fileController->uploadAction($file,$categoryId);

        return $data;
    }

    /**
     * 获取百度编辑器配置
     */
    private function ueditorConfig()
    {
        $config_text    = preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(BASE_PATH . "/public/static/ueditor/config.json"));
        $config         = json_decode($config_text, true);

        $storage = for_storage_config();

        $config['imageAllowFiles'] = array_map([$this, 'ueditorExtension'], explode(',',$storage['image_suffix']));
        $config['videoAllowFiles'] = array_map([$this, 'ueditorExtension'], explode(',',$storage['video_suffix']));
        $config['fileAllowFiles'] = array_map([$this, 'ueditorExtension'], explode(',',$storage['file_suffix']));

        return json_encode($config);
    }

    /**
     * 格式化后缀
     * @param $str
     * @return string
     */
    private function ueditorExtension($str)
    {
        return "." . trim($str, '.');
    }
}
